// 配置路由
import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./routes";
// 引入store
import store from "@/store";
// 使用插件
Vue.use(VueRouter);


// console.log(VueRouter.prototype)
// 先把VueRouter原型对象的push，保存一份
let originPush = VueRouter.prototype.push;
let originReplace = VueRouter.prototype.replace;
// console.log(originPush)
// 重写push｜replace
// 第一个参数：告诉原来push方法，你往哪里跳，以及传递哪些参数
VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(this, location, () => {}, () => {})
  }
};
VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(this, location, () => {}, () => {})
  }
}

let router = new VueRouter({
  // 配置路由
  routes,
  scrollBehavior(to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    return { y: 0 }
  },
});

router.beforeEach(async (to, from, next) => {
  // 用户已登录
  let token = store.state.user.token;
  // 用户信息
  let name = store.state.user.userInfo.name;
  if (token) {
    if (to.path == '/login' || to.path == '/register') {
      next('/')
    } else {
      // 登录，去的不是login 去的是search、home。。。没有用户信息
      if (name) {
        next();
      } else {
        // 获取用户信息
        try {
          // 登录没有用户信息，在跳转之前获取
          // 获取用户信息成功
          await store.dispatch('getUserInfo');
          next();
        } catch (error) {
          // token失效
          //  清除token
          await store.dispatch('userLogout')
          next('/login');
        }
      }
    }
  } else {
    // 用户未登录 无法去 交易相关、支付相关、 个人中心相关
    //    -----     >  先去登录页
    let toPath = to.path;
    console.log(toPath)
    if (toPath.indexOf('/trade') != -1 || toPath.indexOf('/pay') != -1 || toPath.indexOf('/center') != -1) {
      next('/login?redirect=' + toPath);
    } else {
      next();
    }
  }
});

// 配置路由
export default router;
